package cn.seaboot.admin.net.web;

import cn.seaboot.admin.net.manager.HttpClientUtils;
import cn.seaboot.admin.net.prop.HttpClientProperties;
import cn.seaboot.commons.core.Asserts;
import cn.seaboot.commons.exception.BizException;
import cn.seaboot.commons.http.HttpClient;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.hc.core5.http.HttpEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

/**
 * Http映射转发 - Controller
 * <p>
 *
 * @author Mr.css on 2018-6-20
 */
@Controller
@RequestMapping("sys/http")
@Tag(name = "Http映射转发 管理")
public class HttpCtrl {

    @Resource
    private HttpClient httpClient;

    @Resource
    private HttpClientProperties httpClientProperties;


    @ResponseBody
    @RequestMapping("data")
    public int data(@RequestParam Map<String, Object> map) {
        return 1;
    }

    /**
     * 功能类似于 nginx 的反向代理
     */
    @Operation(description = "Http代理转发")
    @RequestMapping(value = "proxy/{urlName}/")
    public void saveInfo(@PathVariable String urlName, HttpServletRequest req, HttpServletResponse res) throws IOException {
        String url = httpClientProperties.getProxy().get(urlName);
        if (url == null) {
            throw new BizException("未知的 http 接口: " + urlName);
        } else {
            HttpClientUtils
                    .forward(httpClient.getOriginalHttpClient(), req, url)
                    .execute(response -> {
                        HttpClientUtils.checkStatus(response);
                        HttpEntity entity = response.getEntity();
                        Asserts.notNull(entity, "http response entity is null!");
                        entity.writeTo(res.getOutputStream());
                        return null;
                    });
        }
    }
}
